from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from typing import List
from app.models.student import Student as StudentModel, StudentInDB
from app.schemas.student import Student as StudentSchema, StudentCreate, StudentUpdate
from app.schemas.response import APIResponse, PaginatedResponse
from app.config.database import get_db
from app.utils.responses import success_response, error_response, paginated_response
from app.utils.logger import logger
from datetime import datetime

router: APIRouter = APIRouter(prefix="/students", tags=["学生管理"])

@router.post("/create", response_model=APIResponse[StudentSchema])
def create_student(student: StudentCreate, db: Session = Depends(get_db)):
    logger.info(f"Creating student with student_no: {student.student_no}")
    
    # 检查学号是否已存在
    db_student = db.query(StudentModel).filter(StudentModel.student_no == student.student_no).first()
    if db_student:
        logger.warning(f"Student number already registered: {student.student_no}")
        return error_response(message="Student number already registered", code=400)
    
    # 创建新学生
    db_student = StudentModel(
        user_id=student.user_id,
        student_no=student.student_no,
        student_name=student.student_name,
        gender=student.gender,
        birth_date=student.birth_date,
        id_card=student.id_card,
        phone=student.phone,
        address=student.address,
        parent_name=student.parent_name,
        parent_phone=student.parent_phone,
        status=student.status,
        create_time=datetime.utcnow(),
        update_time=datetime.utcnow()
    )
    
    db.add(db_student)
    db.commit()
    db.refresh(db_student)
    
    # 转换为Pydantic模型
    student_response = StudentInDB.model_validate(db_student)
    
    logger.info(f"Student created successfully with ID: {db_student.id}")
    return success_response(data=student_response, message="Student created successfully")

@router.get("/list", response_model=APIResponse[PaginatedResponse[StudentSchema]])
def read_students(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
    logger.info(f"Fetching students with skip: {skip}, limit: {limit}")
    
    students = db.query(StudentModel).offset(skip).limit(limit).all()
    # 转换为Pydantic模型
    students_response = [StudentInDB.model_validate(student) for student in students]
    total = db.query(StudentModel).count()
    
    logger.info(f"Found {len(students)} students")
    return paginated_response(
        items=students_response,
        total=total,
        page=skip // limit + 1,
        size=limit
    )

@router.get("/{student_id}", response_model=APIResponse[StudentSchema])
def read_student(student_id: int, db: Session = Depends(get_db)):
    logger.info(f"Fetching student with ID: {student_id}")
    
    db_student = db.query(StudentModel).filter(StudentModel.id == student_id).first()
    if db_student is None:
        logger.warning(f"Student not found with ID: {student_id}")
        return error_response(message="Student not found", code=404)
    
    # 转换为Pydantic模型
    student_response = StudentInDB.model_validate(db_student)
    
    logger.info(f"Student found with ID: {student_id}")
    return success_response(data=student_response)

@router.put("/{student_id}", response_model=APIResponse[StudentSchema])
def update_student(student_id: int, student: StudentUpdate, db: Session = Depends(get_db)):
    logger.info(f"Updating student with ID: {student_id}")
    
    db_student = db.query(StudentModel).filter(StudentModel.id == student_id).first()
    if db_student is None:
        logger.warning(f"Student not found with ID: {student_id}")
        return error_response(message="Student not found", code=404)
    
    # 更新学生信息
    update_data = student.dict(exclude_unset=True)
    for key, value in update_data.items():
        setattr(db_student, key, value)
    
    db_student.update_time = datetime.utcnow()
    db.commit()
    db.refresh(db_student)
    
    # 转换为Pydantic模型
    student_response = StudentInDB.model_validate(db_student)
    
    logger.info(f"Student updated successfully with ID: {student_id}")
    return success_response(data=student_response, message="Student updated successfully")

@router.delete("/{student_id}", response_model=APIResponse[None])
def delete_student(student_id: int, db: Session = Depends(get_db)):
    logger.info(f"Deleting student with ID: {student_id}")
    
    db_student = db.query(StudentModel).filter(StudentModel.id == student_id).first()
    if db_student is None:
        logger.warning(f"Student not found with ID: {student_id}")
        return error_response(message="Student not found", code=404)
    
    db.delete(db_student)
    db.commit()
    
    logger.info(f"Student deleted successfully with ID: {student_id}")
    return success_response(message="Student deleted successfully")